package com.gingko.duominuo.viewmodel

import androidx.hilt.Assisted
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import com.gingko.duominuo.data.Resource
import com.gingko.duominuo.data.asResource
import com.gingko.duominuo.data.datastore.DataStoreHelper
import com.gingko.duominuo.data.isSuccess
import com.gingko.duominuo.data.model.UserVo
import com.gingko.duominuo.data.request.LoginReqVo
import com.gingko.duominuo.data.source.repository.GinkgoRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class LoginViewModel @ViewModelInject constructor(
    private val ginkgoRepository: GinkgoRepository,
    @Assisted val state: SavedStateHandle
) : BaseViewModel() {


    private val _sendCodeLiveData = MutableLiveData<Resource<String>>()
    val sendCodeLiveData: LiveData<Resource<String>> = _sendCodeLiveData
    private val _loginLiveData = MutableLiveData<Resource<UserVo>>()
    val loginLiveData: LiveData<Resource<UserVo>> = _loginLiveData

    fun login(loginReqVo: LoginReqVo) {
        launchOnUI(
            task = {
                _loginLiveData.value = ginkgoRepository.login(loginReqVo).asResource()
            },
            onFailure = {
                _loginLiveData.value = Resource.Error(it)
            }
        )
    }

    fun sendSmsCode(phoneNumber: String) {
        launchOnUI(
            task = {
                _sendCodeLiveData.value = ginkgoRepository.sendSMSCode(phoneNumber).asResource()
            }, onFailure = {
                _sendCodeLiveData.value = Resource.Error(it)
            }
        )
    }

}